package org.ax.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.ax.pojo.sys.Permission;
import org.ax.pojo.sys.User;
import org.ax.service.sys.PermissionService;
import org.ax.service.sys.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;


/**
 * 编程人:赵浩鑫
 * 时间:2021-01-28-10:26
 */
@Slf4j
public class UserRealm extends AuthorizingRealm {
    @Autowired
    PermissionService permissionService;
    @Autowired
    UserService userService;


    @Override //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User user=(User)principalCollection.getPrimaryPrincipal();
        log.debug(user.toString());
        List<Permission> permissions = permissionService.toUserIdFindPerm(user.getId());
        Set<String> perms=new HashSet<String>();
        perms.add("shouquan");
        permissions.forEach(permission -> perms.add(permission.getPercode()));
        log.debug("权限:"+perms.toString());
        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addStringPermissions(perms);
        return simpleAuthorizationInfo;
    }

    @Override //认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userName =(String)token.getPrincipal();//获取凭证
        User user = userService.login(userName);
        if(user==null){
            return null;
        }
        return new SimpleAuthenticationInfo(user, user.getPassword(),super.getName());
    }
}
